//
//  ThemeEditorsViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/28.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "ThemeEditorsViewController.h"
#import "ThemeEditorsCell.h"
#import "ThemeEditorModel.h"
#import "JKBrowserViewController.h"

@interface ThemeEditorsViewController ()

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;
@end

@implementation ThemeEditorsViewController

static NSString *editorReuseID = @"editorCell";

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBarView.title = @"主编";
    self.tableView.rowHeight = 44;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ThemeEditorsCell class]) bundle:nil] forCellReuseIdentifier:editorReuseID];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.editors.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ThemeEditorsCell *cell = [tableView dequeueReusableCellWithIdentifier:editorReuseID];
    
    ThemeEditorModel *model = self.editors[indexPath.row];
    
    cell.editorModel = model;
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [cell changeToNightSkin];
        
    }else{
        [cell changeToDaySkin];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ThemeEditorModel *model = self.editors[indexPath.row];
    
    NSString *urlStr = !model.url ? @"https://zhuanlan.zhihu.com/p/19871622" : model.url;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    JKBrowserViewController *vc = [[JKBrowserViewController alloc] init];
    vc.request = request;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.currentSkinModel = currentSkinModel;
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        self.view.backgroundColor = JKNightSkinColor;
        [self.navBarView changeToNightSkin];
        
    }else{ // 日间模式
        self.view.backgroundColor = JKGlobalBgColor;
        [self.navBarView changeToDaySkin];
    }
    
    [self.tableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
